import json
from urllib.parse import unquote

from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from polls.captcha import Captcha
from polls.models import Subject, Teacher, User
from polls.utils import gen_code, gen_md5_digest


def show_subjects(request: HttpRequest) -> HttpResponse:
    subjects = Subject.objects.all().order_by('no')
    return render(request, 'subjects.html', {
        'subjects': subjects
    })


def show_teachers(request: HttpRequest) -> HttpResponse:
    try:
        sno = int(request.GET.get('sno'))
        teachers = []
        if sno:
            subject = Subject.objects.only('name').get(no=sno)
            teachers = Teacher.objects.filter(subject=subject).order_by('no')
        return render(request, 'teachers.html', {
            'subject': subject,
            'teachers': teachers
        })
    except (ValueError, Subject.DoesNotExist):
        return redirect('/')


def praise_or_criticize(request: HttpRequest) -> HttpResponse:
    if request.session.get('userid'):
        try:
            tno = int(request.GET.get('tno'))
            teacher = Teacher.objects.get(no=tno)
            if request.path.startswith('/praise/'):
                teacher.good_count += 1
                count = teacher.good_count
            else:
                teacher.bad_count += 1
                count = teacher.bad_count
            teacher.save()
            # return redirect(f'/teachers/?sno={sno}')
            data = {'code': 20000, 'message': '投票成功', 'count': count}
        except (ValueError, Teacher.DoesNotExist):
            # return redirect('/')
            data = {'code': 20001, 'message': '投票失败'}
    else:
        data = {'code': 20002, 'message':'请先登录'}
    # return HttpResponse(json.dumps(data), content_type='application/json')
    return JsonResponse(data)


def get_captcha(request: HttpRequest) -> HttpResponse:
    code = gen_code()
    request.session['captcha'] = code
    image_data = Captcha.instance().generate(code)
    return HttpResponse(image_data, content_type='image/png')


def login(request: HttpRequest) -> HttpResponse:
    hint = ''
    backurl = request.GET.get('backurl', '/')
    if request.method == 'POST':
        backurl = request.POST.get('backurl', '/')
        if backurl != '/':
            backurl = unquote(backurl)
        captchar_from_serv = request.session.get('captcha', '0')
        captchar_from_user = request.POST.get('captcha', '1')
        if captchar_from_serv.lower() == captchar_from_user.lower():
            username = request.POST.get('username')
            password = request.POST.get('password')
            if username and password:
                password = gen_md5_digest(password)
                user = User.objects.filter(username=username, password=password).first()
                if user:
                    request.session['userid'] = user.no
                    request.session['username'] = user.username
                    return redirect(backurl)
                else:
                    hint = '用户名或密码错误'
            else:
                hint = '请输入有效的用户名和密码'
        else:
            hint = '验证码有误，请重新输入'
    return render(request, 'login.html', {
        'hint': hint,
        'backurl': backurl,
    })


def logout(request: HttpRequest) -> HttpResponse:
    request.session.flush()
    return redirect('/')


def register(request: HttpRequest) -> HttpResponse:
    hint = ''
    if request.method == 'POST':
        agreement = request.POST.get('agreement')
        user = User()
        if agreement:
            user.username = request.POST.get('username')
            user.password = request.POST.get('password')
            user.tel = request.POST.get('tel')
            if user.username and user.password and user.tel:
                try:
                    user.password = gen_md5_digest(user.password)
                    user.save()
                    return redirect('/login/')
                except:
                    hint = '该用户名已被使用'
            else:
                hint = '请将注册信息填写完整'
        else:
            hint = '请勾选用户协议'
    return render(request, 'register.html', {'hint': hint})























